<?php

namespace App\Http\Controllers\CRM;

use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\CRM\TableEditRequest;
use App\Http\Resources\CRM\TableListResource;
use App\Http\Resources\CRM\TableOrderResource;
use App\Http\Resources\CRM\TableTypeResource;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use App\Models\Table;
use Illuminate\Http\Request;

class TableController extends Controller
{
    public function getTableTypes(Store $store, \App\Enums\TableType $type)
    {
        $tableTypes = $store->tableTypes()
            ->withType($type)
            ->with(['tables.tableOrder.items.assistantUser', 'costRules', 'defaultRule'])
            ->get();

        return TableTypeResource::collection($tableTypes);
    }

    public function getTableInfo(Store $store, Table $table)
    {
        return new TableListResource($table);
    }

    public function editTable(Store $store, Table $table, TableEditRequest $request)
    {
        $table->update($request->only([
            'name', 'sort', 'people_count'
        ]));

        return new TableListResource($table);
    }

    public function getTableQR(Store $store, Table $table)
    {
        return ApiResponseHelper::json([
            'url' => $table->getQRLink()
        ]);
    }

    public function getTableOrders(store $store, Table $table)
    {
        $orderIds = OrderItem::where('table_id', $table->id)->pluck('order_id')->toArray();
        $orders = Order::whereIn('id', $orderIds)
            ->with(['items.assistantUser', 'items.goods'])->latest()->paginate();

        return TableOrderResource::collection($orders);
    }

    public function removeTable(Store $store, Table $table)
    {
        $table->delete();

        return ApiResponseHelper::json([]);
    }
}
